package miiteen.customsportal.login.service;

import miiteen.common.json.JsonUtil;
import miiteen.customsportal.login.beans.LoginOrganizationInfo;
import miiteen.customsportal.login.dao.LoginOrganizationInfoDao;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import miiteen.data.dao.BaseDao;
import miiteen.data.service.impl.BaseServiceImpl;

import miiteen.customsportal.login.beans.LoginUserInfo;
import miiteen.customsportal.login.dao.LoginUserInfoDao;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *Name: CustomsPortal_Login_UserInfo
 *Des: -Service
 *Author: ycx
 *Date: 2020-08-27
 */
@Service("loginUserInfoService")
public class LoginUserInfoService extends BaseServiceImpl<LoginUserInfo>{

	@Autowired
	private LoginUserInfoDao loginUserInfoDao;

	@Override
	protected BaseDao<LoginUserInfo> getDao() {
		return loginUserInfoDao;
	}


	@Autowired
	private LoginOrganizationInfoDao organizationInfoDao;

	@Transactional
	public long save(LoginUserInfo loginUserInfo){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userGuid",loginUserInfo.getUserGuid());
		List<LoginUserInfo> listByMap = loginUserInfoDao.findListByMap(map);
		if(listByMap != null && listByMap.size() >0){
			loginUserInfo .setId(listByMap.get(0).getId());
			if(listByMap.size()==1){
				loginUserInfo.setLoginOrganizationInfoList(listByMap.get(0).getLoginOrganizationInfoList());
			}
		}
		loginUserInfo.setLatestLoginTime(new Date());//修改时间
		long result = loginUserInfoDao.save(loginUserInfo);
		if(result >0 ) {
			/*map.clear();
			map.put("userid" ,result+"");
			List<LoginOrganizationInfo> listByMap1 = organizationInfoDao.findListByMap(map);
			if(listByMap1 != null && listByMap1.size() >0){// 先删除
				String ids="";
				for(LoginOrganizationInfo loginOrganizationInfo :listByMap1){
					if("".equals(ids)){
						ids=String.valueOf(loginOrganizationInfo.getId());
					}else{
						ids=ids+","+String.valueOf(loginOrganizationInfo.getId());
					}

				}
				organizationInfoDao.delete(ids);
			}*/
			//在增加
			List<LoginOrganizationInfo> loginOrganizationInfoList = loginUserInfo.getLoginOrganizationInfoList();
			if(loginOrganizationInfoList != null && loginOrganizationInfoList.size() >0){
				for(LoginOrganizationInfo LoginOrganizationInfo :loginOrganizationInfoList){
					LoginOrganizationInfo.setUserid(result);
					LoginOrganizationInfo.setUserGuid(loginUserInfo.getUserGuid());
					organizationInfoDao.save(LoginOrganizationInfo);
				}
			}

		}

		return result;
	}
	
}